﻿using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Web;
using System.Linq;

namespace SimpleCMS.Models
{
    [Table("News")]
    public class News
    {
        public int ID { get; set; }
        [Display(Name = "发布时间"), DataType(DataType.DateTime)]
        public DateTime Time { get; set; }
        [Display(Name = "标题"), StringLength(20, MinimumLength = 1)]
        public string Title { get; set; }
        [Display(Name = "内容"), Required]
        public string Content { get; set; }
        public long EditorID { get; set; }
        [Display(Name = "点击量")]
        public long ClickCount { get; set; }
        [Display(Name = "状态"), Range(0, 3)]
        public int Status { get; set; }
        [Display(Name = "标签")]
        public string Tags { get; set; }
        [Required]
        public int GenreID { get; set; }

        private string editor = null;
        [NotMapped, Display(Name = "编辑")]
        public string Editor
        {
            get
            {
                if (editor == null)
                {
                    NewsDBContext db = new NewsDBContext();
                    User u = db.Users.FirstOrDefault(x => x.ID == EditorID);
                    if (u != null)
                        editor = u.UserName;
                }
                return editor;
            }
        }

        private string genre = null;
        [NotMapped, Display(Name = "版块")]
        public string Genre
        {
            get
            {
                if (genre == null)
                {
                    NewsDBContext db = new NewsDBContext();
                    Genre g = db.Genres.FirstOrDefault(x => x.ID == GenreID);
                    if (g != null)
                        genre = g.Name;
                }
                return genre;
            }
        }
    }

    [Table("Genre")]
    public class Genre
    {
        public int ID { get; set; }
        [Display(Name = "创建时间")]
        public DateTime Time { get; set; }
        [Display(Name = "名称")]
        public string Name { get; set; }
        [Display(Name = "负责人")]
        public int Manager { get; set; }
    }

    public class NewsDBContext : DbContext
    {
        public NewsDBContext() : base("DefaultConnection") { }
        public DbSet<News> News { get; set; }
        public DbSet<Genre> Genres { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<Role> Roles { get; set; }
    }
}